package ${cfg.package_dir}.${cfg.cfgName};

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import ${cfg.package_dir}.common.Result;

import java.util.ArrayList;
/*
HttpStatus.OK = 200;
HttpStatus.BAD_REQUEST = 400;
HttpStatus.FORBIDDEN = 403;
HttpStatus.NOT_FOUND = 404;
HttpStatus.REQUEST_TIMEOUT = 408;
HttpStatus.SERVICE_UNAVAILABLE =500;
 */
@Slf4j
@RestControllerAdvice //拦截异常并统一处理
public class GlobalExceptionConf{
    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    @ExceptionHandler(value = IllegalArgumentException.class)
    public Result handler(IllegalArgumentException e) {
        log.error("----------------Assert异常-------------------", e);
        return Result.fail(-10,e.getMessage());
    }

    @ResponseStatus(HttpStatus.SERVICE_UNAVAILABLE)
    @ExceptionHandler(value = RuntimeException.class)
    public Result handler(RuntimeException e) {
        log.error("----------------运行时异常-------------------", e);
        return Result.fail(-10,e.getMessage());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = { MethodArgumentNotValidException.class }) // , BindException.class
    public Result handler(MethodArgumentNotValidException e) {
        log.error("----------------实体校验异常-------------------------");
        BindingResult bindingResult = e.getBindingResult();
        ArrayList<String> strings = new ArrayList<>();
        bindingResult.getAllErrors().stream().forEach(ele->{strings.add(ele.getDefaultMessage()); } );
        return Result.success(strings);
    }

}
